<template>
  <div class="addAdvertise">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      size="default"
      status-icon
    >
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select v-model="ruleForm.parentId">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量单位" prop="productUnit">
        <el-input v-model="ruleForm.productUnit" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" />
      </el-form-item>
      <el-form-item label="是否显示" prop="showStatus">
        <el-radio-group v-model="ruleForm.showStatus">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否显示在导航栏" prop="navStatus">
        <el-radio-group v-model="ruleForm.navStatus">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类图标" prop="icon">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="http://xue.cnkdl.cn:9082/mall-admin/minio/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture"
          :on-success="handleSuccess"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过100kb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="筛选属性" prop="productAttributeIdList">
        <div v-for="(item, index) in casOptioList" :key="item.name">
          <el-cascader
            v-model="item.name"
            :options="casOption"
            :props="{
              label: 'name',
              value: 'id',
              children: 'productAttributeList',
              emitPath: false,
            }"
          >
          </el-cascader>
          <el-button type="primary" plain @click="delList(index)"
            >删除</el-button
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addList">新增</el-button>
      </el-form-item>
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="ruleForm.keywords" />
      </el-form-item>
      <el-form-item label="分类描述" prop="description">
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          placeholder="请输入内容"
          style="width: 80%"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadProps,
  type UploadUserFile,
} from "element-plus";
import * as http from "@/request/http";
onMounted(async () => {
  // 获取有无上级
  const res = await http.productCate.proCateListChild({
    id: 0,
    pageSize: 100,
    pageNum: 1,
  });
  options.value = res.data.list;
  options.value.push({
    name: "无上级分类",
    id: 0,
  });

  // 获取 筛选属性
  const res2 = http.productCate.getCategoryList();
  casOption.value = (await res2).data;
  console.log("筛选数据", casOption.value);
});
// 有无上级
let options: any = ref([]);
// 筛选
let casOption: any = ref([]);

// 筛选的数组
let casOptioList = ref([
  {
    name: 1,
  },
]);

// 添加筛选的条件
const addList = () => {
  if (casOptioList.value.length === 3) {
    ElMessage.warning("最多添加3个啊~~~~~~");
    return;
  }
  casOptioList.value.push({ name: casOptioList.value.length });
};

// 删除
const delList = (i: number) => {
  if (casOptioList.value.length === 1) {
    ElMessage.warning("最少留下一个啊~~~~~");
    return;
  }
  casOptioList.value.splice(i, 1);
};

interface RuleForm {
  // 分类名称
  name: string;
  // 上级分类
  parentId: number;
  // 数量单位
  productUnit: "";
  // 排序
  sort: number;
  // 是否显示
  showStatus: number;
  // 是否显示在导航栏
  navStatus: number;
  // 分类图标
  icon: any;
  // 筛选属性
  productAttributeIdList: any;
  // 关键词
  keywords: string;
  // 分类描述
  description: string;
}

//图片的qpi
const fileList = ref<UploadUserFile[]>([]);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

// 实例
const ruleFormRef = ref<FormInstance>();
// 表单
const ruleForm = reactive<RuleForm>({
  name: "",
  parentId: 0,
  productUnit: "",
  sort: 0,
  showStatus: 1,
  navStatus: 1,
  icon: "",
  productAttributeIdList: "",
  keywords: "",
  description: "",
});

const handlePreview: UploadProps["onPreview"] = (file) => {
  console.log(file);
};
// 上传成功的回调
const handleSuccess: UploadProps["onSuccess"] = (uploadFile, uploadFiles) => {
  console.log("上传的回调", uploadFile.data);
  console.log("本地的回调", uploadFiles);
  ruleForm.icon = uploadFile.data.url;
};

// 自定义规则
// const validatePass = (_rule: any, value: any, callback: any) => {
//   const flg = /^(http|https):\/\/([\w-]+\.)+[\w]+(:\d+)?(\/.*)?$/;
//   if (value === "") {
//     callback(new Error("请输入地址"));
//   } else if (!flg.test(value)) {
//     callback(new Error("请填写正确格式"));
//   } else {
//     callback();
//   }
// };

// 校验规则
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
});

// 点击提交
const submitForm = async (formEl: FormInstance | undefined) => {
  const arr = casOptioList.value.map((item) => item.name);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(1);
      ElMessageBox.confirm("是否提交数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("表单", ruleForm);
          http.productCate
            .productCategoryCreate({
              ...ruleForm,
              productAttributeIdList: arr,
            })
            .then((res) => {
              if (res.code === 200) {
                ElMessage.success("成功提交");
                ruleFormRef.value?.resetFields();
              }
            });
        })
        .catch(() => {
          ElMessage.error("取消提交");
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="less" scoped>
.addAdvertise {
  width: 60%;
  margin: 50px auto;
  border: 2px solid #f5f5f5;
  padding: 50px 50px;
  .el-input {
    width: 60%;
  }

  .el-form-item {
    :deep(.el-form-item__label) {
      width: 140px !important;
    }
  }
}
</style>
